import axios from 'axios';
import router from '@/router';
import { Toast } from 'vant';
import store from '@/store';

let baseURL = '';
const post = function(url, data, loading = true) {
  baseURL = store.state.globalConfig.api + url;
  const userInfo = store.state.userInfo;
  if (loading) {
    Toast.loading({
      forbidClick: true,
      loadingType: 'spinner',
      duration: 0,
    });
  }
  if (userInfo) {
    axios.defaults.headers.post['token'] = userInfo.token;
  }
  axios.defaults.timeout = 500000;
  return new Promise((resolve, reject) => {
    axios
      .post(baseURL, data)
      .then((res) => {
        if (res.data.errorcode === 600) {
          Toast({
            message: res.data.msg,
            duration: 2200,
          });
        } else if (res.data.errorcode === 500) {
          resolve(res.data);
          Toast({
            message: res.data.msg,
            duration: 2200,
          });
        } else if (res.data.errorcode === 700) {
          Toast.clear();
          router.push('/login');
        } else if (res.data.errorcode === 200) {
          resolve(res.data);
          Toast.clear();
        }
      })
      .catch((err) => {
        reject(err.data);
        Toast.clear();
      });
  });
};
export default {
  post,
};
